<?php
/**
 * Created by PhpStorm.
 * User: work
 * Date: 18-8-4
 * Time: 下午3:40
 */

namespace PddWechat\Models\Share\Data;


use Dai\Framework\Library\Log;
use Dai\Framework\Library\RedisExt;
use PddWechat\Library\ImageLibrary;
use PddWechat\Library\WechatLibrary;
use PddWechat\Models\Share\Dao\ShareQrDao;
use PddWechat\Models\Share\DataObject\ShareQrDo;

class ShareQrData
{
    public function __construct()
    {
        $this->shareQrDao = new ShareQrDao();
    }

    public function insert(ShareQrDo $shareQrDo)
    {
        return $this->shareQrDao->insert($shareQrDo);
    }

    public function selectMediaId(string $openId)
    {
        return $this->shareQrDao->selectMediaId($openId);
    }



    /**
     * 获得邀请好友的mediaId
     */
    public function getInviteMediaId($openId){
        $redisKey = "qrcode_". $openId;
        $redisValue = RedisExt::getInstance()->get($redisKey);
        if( ! empty($redisValue)) {
            return $redisValue;
        }

        $record = $this->selectMediaId($openId);
        $invitePath =  IMAGE_PATH."invite/$openId.jpg";
        if(empty($record)) {
            //首先去获得该用户的二维码
            $qrTicket = WechatLibrary::getQrCodeTicket($openId);
            $qrUlr = WechatLibrary::getQrCodeImage($qrTicket);
            $qrImageData  = file_get_contents($qrUlr);
            $qCodePath = IMAGE_PATH."qr/$openId.jpg";
            if( trim($qrImageData) == null) {
                Log::error("生成二维码失败, $qrUlr, $invitePath");
                return false;
            }else {
                Log::info("获取二维码成功  url $qrUlr, path $qCodePath, invite $invitePath");
            }
            file_put_contents($qCodePath, $qrImageData);
            ImageLibrary::mergeQr(APP_PATH."/static/image/qr_back.jpg", $qCodePath, $invitePath);
        }
        //搞定mediaId
        $mediaRes = WechatLibrary::sendGetMediaId($invitePath, "image");

        $shareQrDo = new ShareQrDo();
        $shareQrDo->openId = $openId;
        $shareQrDo->ticket = $qrTicket;
        $shareQrDo->path = $invitePath;
        $shareQrDo->expireTime = date('Y-m-d H:i:s', time() + 86400 * 5);
        $shareQrDo->mediaId= $mediaRes->media_id;
        $this->insert($shareQrDo);
        RedisExt::getInstance()->setex($redisKey, 86400 * 2.5, $mediaRes->media_id);
        return $mediaRes->media_id;
    }
}